/**
 * 院校与企业页面JavaScript
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化各功能模块
    initTabSwitcher();
    initFilterBar();
    initViewOptions();
    initTabBar();
    
    // 初始化地理位置功能
    initUserLocation();
    
    // 加载院校数据
    loadSchools();
    
    // 处理图片加载错误
    handleImageErrors();
    
    // 添加页面滚动事件监听
    window.addEventListener('scroll', function() {
        // 延迟检查图片加载状态
        if (window.scrollY > 50 && !window._imagesChecked) {
            window._imagesChecked = true;
            setTimeout(() => {
                document.querySelectorAll('.institution-logo').forEach(img => {
                    if (img.complete && img.naturalHeight === 0) {
                        replaceWithAlternativeImage(img);
                    }
                    
                    // 确保图片容器有正确的类名
                    const container = img.closest('.institution-logo-container');
                    if (container && img.complete && img.naturalHeight > 0) {
                        container.classList.add('image-loaded');
                        img.classList.add('image-loaded');
                    }
                });
            }, 500);
        }
    });
    
    // 在切换标签时重新检查图片
    const tabs = document.querySelectorAll('.category-tabs .tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 延迟以确保DOM更新
            setTimeout(() => {
                handleImageErrors();
            }, 300);
        });
    });
});

/**
 * 初始化分类标签切换
 */
function initTabSwitcher() {
    const tabs = document.querySelectorAll('.category-tabs .tab');
    const schoolFilter = document.querySelector('#school-filter');
    const companyFilter = document.querySelector('#company-filter');
    const schoolList = document.querySelector('#school-list');
    const companyList = document.querySelector('#company-list');
    
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有标签的active类
            tabs.forEach(t => t.classList.remove('active'));
            
            // 为当前点击的标签添加active类
            this.classList.add('active');
            
            const target = this.getAttribute('data-target');
            
            // 显示对应的筛选器和列表
            if (target === 'schools') {
                schoolFilter.classList.add('active');
                companyFilter.classList.remove('active');
                schoolList.classList.add('active');
                companyList.classList.remove('active');
                loadSchools(); // 切换到院校标签时重新加载数据
            } else {
                schoolFilter.classList.remove('active');
                companyFilter.classList.add('active');
                schoolList.classList.remove('active');
                companyList.classList.add('active');
                loadCompanies(); // 切换到企业标签时加载企业数据
            }
        });
    });
    
    // 默认激活第一个标签
    tabs[0].click();
}

/**
 * 初始化筛选器
 */
function initFilterBar() {
    // 为筛选选择器添加变化事件
    const filters = document.querySelectorAll('.filter-select');
    
    filters.forEach(filter => {
        filter.addEventListener('change', function() {
            // 获取当前激活的列表
            const activeList = document.querySelector('.institutions-list.active');
            
            // 根据筛选条件过滤和显示数据
            filterInstitutions(activeList);
        });
    });
}

/**
 * 根据筛选条件过滤数据
 */
function filterInstitutions(listElement) {
    // 获取激活的筛选器
    const activeFilter = document.querySelector('.filter-bar.active');
    
    if (!activeFilter) return;
    
    // 获取筛选值
    const region = activeFilter.querySelector('[name="region"]').value;
    const type = activeFilter.querySelector('[name="type"]').value;
    const feature = activeFilter.querySelector('[name="feature"]').value;
    
    // 获取所有卡片
    const cards = listElement.querySelectorAll('.institution-card');
    
    cards.forEach(card => {
        const cardRegion = card.getAttribute('data-region');
        const cardType = card.getAttribute('data-type');
        const cardFeatures = card.getAttribute('data-features');
        
        // 判断是否符合筛选条件
        const matchRegion = region === 'all' || cardRegion === region;
        const matchType = type === 'all' || cardType === type;
        const matchFeature = feature === 'all' || (cardFeatures && cardFeatures.includes(feature));
        
        // 显示或隐藏卡片
        if (matchRegion && matchType && matchFeature) {
            card.style.display = '';
        } else {
            card.style.display = 'none';
        }
    });
}

/**
 * 初始化视图选项
 */
function initViewOptions() {
    // 网格和列表视图切换
    const gridBtn = document.querySelector('.view-btn[data-view="grid"]');
    const listBtn = document.querySelector('.view-btn[data-view="list"]');
    const institutionsLists = document.querySelectorAll('.institutions-list');
    
    gridBtn.addEventListener('click', function() {
        gridBtn.classList.add('active');
        listBtn.classList.remove('active');
        
        institutionsLists.forEach(list => {
            list.classList.remove('list-view');
        });
    });
    
    listBtn.addEventListener('click', function() {
        listBtn.classList.add('active');
        gridBtn.classList.remove('active');
        
        institutionsLists.forEach(list => {
            list.classList.add('list-view');
        });
    });
    
    // 排序选项
    const sortOptions = document.querySelectorAll('.sort-option');
    
    sortOptions.forEach(option => {
        option.addEventListener('click', function() {
            // 移除所有排序选项的active类
            sortOptions.forEach(o => o.classList.remove('active'));
            
            // 为当前点击的选项添加active类
            this.classList.add('active');
            
            // 获取排序方式
            const sortBy = this.getAttribute('data-sort');
            
            // 获取当前活动的列表
            const activeList = document.querySelector('.institutions-list.active');
            
            // 排序列表
            sortInstitutions(activeList, sortBy);
        });
    });
}

/**
 * 根据指定条件排序院校/企业
 */
function sortInstitutions(listElement, sortBy) {
    const cards = Array.from(listElement.querySelectorAll('.institution-card'));
    
    cards.sort((a, b) => {
        switch(sortBy) {
            case 'recommend':
                // 按推荐指数排序（降序）
                return parseInt(b.getAttribute('data-recommend') || 0) - 
                       parseInt(a.getAttribute('data-recommend') || 0);
            case 'hot':
                // 按热度排序（降序）
                return parseInt(b.getAttribute('data-hot') || 0) - 
                       parseInt(a.getAttribute('data-hot') || 0);
            case 'latest':
                // 按最新排序（降序）
                return parseInt(b.getAttribute('data-latest') || 0) - 
                       parseInt(a.getAttribute('data-latest') || 0);
            default:
                return 0;
        }
    });
    
    // 重新添加排序后的卡片
    cards.forEach(card => {
        listElement.appendChild(card);
    });
}

/**
 * 初始化底部导航栏
 */
function initTabBar() {
    const tabs = document.querySelectorAll('.tab-bar .tab');
    
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const target = this.getAttribute('data-target');
            
            if (target) {
                window.location.href = target;
            }
        });
    });
}

/**
 * 初始化用户位置功能
 */
function initUserLocation() {
    const locationElement = document.getElementById('user-location');
    const locationText = locationElement.querySelector('.location-text');
    
    // 默认位置
    const defaultLocation = '北京市';
    
    // 检查是否已有缓存的位置信息
    const cachedLocation = localStorage.getItem('userLocation');
    const cachedTimestamp = localStorage.getItem('locationTimestamp');
    const locationAge = cachedTimestamp ? (Date.now() - parseInt(cachedTimestamp)) / (1000 * 60 * 60) : 24; // 转换为小时
    
    // 如果有缓存且不超过12小时，直接使用缓存
    if (cachedLocation && locationAge < 12) {
        locationText.textContent = cachedLocation;
        // 添加点击事件以重新获取位置
        locationElement.addEventListener('click', getUserLocation);
        return;
    }
    
    // 获取用户地理位置
    getUserLocation();
    
    // 添加点击事件以重新获取位置
    locationElement.addEventListener('click', getUserLocation);
    
    // 地理位置获取函数
    function getUserLocation() {
        // 显示正在定位状态
        locationText.textContent = '定位中...';
        
        // 检查浏览器是否支持地理定位
        if (navigator.geolocation) {
            // 添加加载动画
            locationElement.classList.add('locating');
            
            // 尝试获取位置
            navigator.geolocation.getCurrentPosition(
                // 成功回调
                function(position) {
                    // 使用位置坐标获取城市名称
                    getCityNameFromCoords(position.coords.latitude, position.coords.longitude);
                },
                // 错误回调
                function(error) {
                    console.error('位置获取失败:', error);
                    // 降级到IP定位
                    getCityFromIP();
                },
                // 选项
                { 
                    enableHighAccuracy: false, // 不需要高精度
                    timeout: 5000, // 5秒超时
                    maximumAge: 0 // 不使用缓存
                }
            );
        } else {
            // 浏览器不支持地理定位
            console.log('浏览器不支持地理定位');
            // 降级到IP定位
            getCityFromIP();
        }
    }
    
    // 从坐标获取城市名称（模拟实现，实际应使用地图API）
    function getCityNameFromCoords(latitude, longitude) {
        // 这里应该调用地图服务API，如百度地图、高德地图或天地图等
        // 由于这是模拟实现，我们使用随机城市
        const cities = ['北京市', '上海市', '广州市', '深圳市', '杭州市', '南京市', '成都市', '武汉市', '西安市', '重庆市'];
        const randomCity = cities[Math.floor(Math.random() * cities.length)];
        
        // 模拟API请求延迟
        setTimeout(() => {
            updateLocationDisplay(randomCity);
        }, 1000);
    }
    
    // 从IP获取城市名称（模拟实现）
    function getCityFromIP() {
        // 这里应该调用IP定位服务API
        // 由于这是模拟实现，我们使用随机城市
        const cities = ['北京市', '上海市', '广州市', '深圳市', '杭州市', '南京市', '成都市', '武汉市', '西安市', '重庆市'];
        const randomCity = cities[Math.floor(Math.random() * cities.length)];
        
        // 模拟API请求延迟
        setTimeout(() => {
            updateLocationDisplay(randomCity);
        }, 800);
    }
    
    // 更新位置显示
    function updateLocationDisplay(cityName) {
        locationText.textContent = cityName || defaultLocation;
        
        // 移除加载动画
        locationElement.classList.remove('locating');
        
        // 缓存位置信息
        localStorage.setItem('userLocation', cityName || defaultLocation);
        localStorage.setItem('locationTimestamp', Date.now().toString());
        
        // 触发位置更新事件
        const event = new CustomEvent('locationUpdated', { detail: { location: cityName || defaultLocation } });
        document.dispatchEvent(event);
    }
}

/**
 * 加载院校数据
 */
function loadSchools() {
    // 显示加载动画
    showLoading(true);
    
    try {
        // 模拟院校数据，实际项目中应从API获取
        const schools = [
            {
                id: 1,
                name: '北京大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/1',
                region: 'north',
                type: 'comprehensive',
                features: ['985', '211', 'C9'],
                recommend: 98,
                hot: 95,
                latest: 90,
                bgColor: '#E3F2FD'
            },
            {
                id: 2,
                name: '清华大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/2',
                region: 'north',
                type: 'engineering',
                features: ['985', '211', 'C9'],
                recommend: 99,
                hot: 97,
                latest: 92,
                bgColor: '#E8F5E9'
            },
            {
                id: 3,
                name: '复旦大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/3',
                region: 'east',
                type: 'comprehensive',
                features: ['985', '211', 'C9'],
                recommend: 97,
                hot: 94,
                latest: 88,
                bgColor: '#FFF3E0'
            },
            {
                id: 4,
                name: '上海交通大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/4',
                region: 'east',
                type: 'engineering',
                features: ['985', '211', 'C9'],
                recommend: 96,
                hot: 93,
                latest: 89,
                bgColor: '#E1F5FE'
            },
            {
                id: 5,
                name: '浙江大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/5',
                region: 'east',
                type: 'comprehensive',
                features: ['985', '211', 'C9'],
                recommend: 95,
                hot: 92,
                latest: 87,
                bgColor: '#F3E5F5'
            },
            {
                id: 6,
                name: '南京大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/6',
                region: 'east',
                type: 'comprehensive',
                features: ['985', '211', 'C9'],
                recommend: 94,
                hot: 91,
                latest: 86,
                bgColor: '#FFFDE7'
            },
            {
                id: 7,
                name: '中国人民大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/7',
                region: 'north',
                type: 'comprehensive',
                features: ['985', '211'],
                recommend: 93,
                hot: 90,
                latest: 85,
                bgColor: '#E0F7FA'
            },
            {
                id: 8,
                name: '武汉大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/8',
                region: 'central',
                type: 'comprehensive',
                features: ['985', '211'],
                recommend: 92,
                hot: 89,
                latest: 84,
                bgColor: '#FBE9E7'
            },
            {
                id: 9,
                name: '华中科技大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/9',
                region: 'central',
                type: 'engineering',
                features: ['985', '211'],
                recommend: 91,
                hot: 88,
                latest: 83,
                bgColor: '#F9FBE7'
            },
            {
                id: 10,
                name: '四川大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/10',
                region: 'southwest',
                type: 'comprehensive',
                features: ['985', '211'],
                recommend: 90,
                hot: 87,
                latest: 82,
                bgColor: '#E8EAF6'
            },
            {
                id: 11,
                name: '中山大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/11',
                region: 'south',
                type: 'comprehensive',
                features: ['985', '211'],
                recommend: 89,
                hot: 86,
                latest: 81,
                bgColor: '#FFEBEE'
            },
            {
                id: 12,
                name: '南开大学',
                logo: 'https://source.unsplash.com/random/400x300/?university,campus/12',
                region: 'north',
                type: 'comprehensive',
                features: ['985', '211'],
                recommend: 88,
                hot: 85,
                latest: 80,
                bgColor: '#F1F8E9'
            }
        ];
        
        // 获取院校列表容器
        const schoolList = document.querySelector('#school-list');
        if (!schoolList) {
            throw new Error('找不到院校列表容器');
        }
        
        // 清空列表内容
        schoolList.innerHTML = '';
        
        // 为每个院校创建卡片并添加到列表
        schools.forEach(school => {
            const card = createSchoolCard(school);
            schoolList.appendChild(card);
        });
        
        // 隐藏加载动画
        setTimeout(() => {
            showLoading(false);
        }, 800);
        
        // 添加卡片出现动画
        animateCards(schoolList);
        
    } catch (error) {
        console.error('加载院校数据失败:', error);
        showLoading(false);
        showNoResults();
    }
}

/**
 * 创建院校卡片
 */
function createSchoolCard(school) {
    const card = document.createElement('div');
    card.className = 'institution-card school-card fade-in';
    card.setAttribute('data-region', school.region);
    card.setAttribute('data-type', school.type);
    card.setAttribute('data-features', school.features.join(','));
    card.setAttribute('data-recommend', school.recommend);
    card.setAttribute('data-hot', school.hot);
    card.setAttribute('data-latest', school.latest);
    
    // 添加背景渐变
    card.style.background = `linear-gradient(135deg, ${school.bgColor || '#ffffff'} 0%, #ffffff 100%)`;
    
    // 随机决定是否显示徽章（约30%的卡片会显示）
    const showBadge = Math.random() > 0.7;
    const badgeText = showBadge ? (school.recommend > 95 ? '顶尖高校' : '知名高校') : '';
    
    // 确保有有效的图片URL
    const schoolId = school.id || Math.floor(Math.random() * 1000);
    const logoUrl = `https://source.unsplash.com/featured/400x300/?university,campus/${schoolId}`;
    
    card.innerHTML = `
        <div class="institution-logo-container">
            <img src="${logoUrl}" alt="${school.name}" class="institution-logo" loading="lazy">
            ${showBadge ? `<div class="institution-badge">${badgeText}</div>` : ''}
            <div class="institution-overlay"></div>
        </div>
        <div class="institution-info">
            <h3 class="institution-name">${school.name}</h3>
            <div class="institution-type">${getTypeName(school.type)} · ${getRegionName(school.region)}</div>
            <div class="institution-features">
                ${school.features.map(feature => `<span class="feature-tag"><i class="iconfont icon-tag"></i>${feature}</span>`).join('')}
            </div>
            <div class="institution-stats">
                <div class="stats-item"><i class="iconfont icon-star"></i> ${school.recommend}分</div>
                <div class="stats-item"><i class="iconfont icon-eye"></i> ${school.hot * 10}浏览</div>
            </div>
        </div>
    `;
    
    // 添加点击事件
    card.addEventListener('click', function(event) {
        // 添加点击涟漪效果
        createRippleEffect(this, event);
        // 延迟跳转，以便显示动画
        setTimeout(() => {
            // 跳转到院校详情页
            window.location.href = `school-detail.html?id=${school.id}`;
        }, 300);
    });
    
    return card;
}

/**
 * 创建点击涟漪效果
 */
function createRippleEffect(element, event) {
    const ripple = document.createElement('div');
    ripple.className = 'ripple-effect';
    
    const rect = element.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    ripple.style.left = `${x}px`;
    ripple.style.top = `${y}px`;
    
    element.appendChild(ripple);
    
    setTimeout(() => {
        ripple.remove();
    }, 600);
}

/**
 * 加载企业数据
 */
function loadCompanies() {
    // 显示加载动画
    showLoading(true);
    
    try {
        // 模拟企业数据，实际项目中应从API获取
        const companies = [
            {
                id: 1,
                name: '腾讯科技',
                logo: 'https://source.unsplash.com/featured/400x300/?tech,company/1',
                region: 'south',
                type: 'internet',
                features: ['互联网', '游戏', '社交'],
                size: '10000人以上',
                recommend: 96,
                hot: 99,
                latest: 95,
                bgColor: '#E1F5FE'
            },
            {
                id: 2,
                name: '阿里巴巴',
                logo: 'https://source.unsplash.com/featured/400x300/?tech,company/2',
                region: 'east',
                type: 'internet',
                features: ['互联网', '电商', '云计算'],
                size: '10000人以上',
                recommend: 95,
                hot: 98,
                latest: 94,
                bgColor: '#FFF8E1'
            },
            {
                id: 3,
                name: '华为技术',
                logo: 'https://source.unsplash.com/featured/400x300/?tech,company/3',
                region: 'south',
                type: 'hardware',
                features: ['通信', '硬件', '研发'],
                size: '10000人以上',
                recommend: 97,
                hot: 96,
                latest: 93,
                bgColor: '#F3E5F5'
            },
            {
                id: 4,
                name: '百度',
                logo: 'https://source.unsplash.com/featured/400x300/?search,tech/4',
                region: 'north',
                type: 'internet',
                features: ['互联网', '人工智能', '搜索'],
                size: '10000人以上',
                recommend: 94,
                hot: 95,
                latest: 91,
                bgColor: '#E8F5E9'
            },
            {
                id: 5,
                name: '字节跳动',
                logo: 'https://source.unsplash.com/featured/400x300/?social,tech/5',
                region: 'north',
                type: 'internet',
                features: ['互联网', '内容', '短视频'],
                size: '10000人以上',
                recommend: 98,
                hot: 99,
                latest: 95,
                bgColor: '#E3F2FD'
            },
            {
                id: 6,
                name: '美团',
                logo: 'https://source.unsplash.com/featured/400x300/?food,delivery/6',
                region: 'north',
                type: 'service',
                features: ['生活服务', '互联网', '外卖'],
                size: '10000人以上',
                recommend: 92,
                hot: 94,
                latest: 96,
                bgColor: '#FFFDE7'
            },
            {
                id: 7,
                name: '网易',
                logo: 'https://source.unsplash.com/featured/400x300/?game,tech/7',
                region: 'east',
                type: 'internet',
                features: ['互联网', '游戏', '音乐'],
                size: '10000人以上',
                recommend: 93,
                hot: 92,
                latest: 90,
                bgColor: '#E0F7FA'
            },
            {
                id: 8,
                name: '小米科技',
                logo: 'https://source.unsplash.com/featured/400x300/?phone,tech/8',
                region: 'north',
                type: 'hardware',
                features: ['智能硬件', '互联网', 'IoT'],
                size: '10000人以上',
                recommend: 94,
                hot: 96,
                latest: 92,
                bgColor: '#FBE9E7'
            },
            {
                id: 9,
                name: '京东',
                logo: 'https://source.unsplash.com/featured/400x300/?ecommerce,shopping/9',
                region: 'north',
                type: 'internet',
                features: ['电商', '物流', '零售'],
                size: '10000人以上',
                recommend: 91,
                hot: 93,
                latest: 89,
                bgColor: '#F9FBE7'
            },
            // 新增企业数据
            {
                id: 10,
                name: '中国工商银行',
                logo: 'https://source.unsplash.com/featured/400x300/?bank,finance/10',
                region: 'north',
                type: 'finance',
                features: ['金融', '银行', '投资'],
                size: '10000人以上',
                recommend: 93,
                hot: 90,
                latest: 88,
                bgColor: '#ECEFF1'
            },
            {
                id: 11,
                name: '中国建设银行',
                logo: 'https://source.unsplash.com/featured/400x300/?bank,building/11',
                region: 'north',
                type: 'finance',
                features: ['金融', '银行', '贷款'],
                size: '10000人以上',
                recommend: 92,
                hot: 89,
                latest: 87,
                bgColor: '#E0F2F1'
            },
            {
                id: 12,
                name: '中国人寿',
                logo: 'https://source.unsplash.com/featured/400x300/?insurance,life/12',
                region: 'north',
                type: 'finance',
                features: ['保险', '金融', '理财'],
                size: '10000人以上',
                recommend: 90,
                hot: 88,
                latest: 86,
                bgColor: '#E8F5E9'
            },
            {
                id: 13,
                name: '国家电网',
                logo: 'https://source.unsplash.com/featured/400x300/?energy,power/13',
                region: 'north',
                type: 'manufacturing',
                features: ['能源', '电力', '国企'],
                size: '10000人以上',
                recommend: 91,
                hot: 87,
                latest: 85,
                bgColor: '#FFF3E0'
            },
            {
                id: 14,
                name: '中国石油',
                logo: 'https://source.unsplash.com/featured/400x300/?oil,energy/14',
                region: 'north',
                type: 'manufacturing',
                features: ['能源', '石油', '化工'],
                size: '10000人以上',
                recommend: 89,
                hot: 86,
                latest: 84,
                bgColor: '#FFEBEE'
            },
            {
                id: 15,
                name: '中国移动',
                logo: 'https://source.unsplash.com/featured/400x300/?mobile,telecom/15',
                region: 'north',
                type: 'service',
                features: ['通信', '运营商', '网络'],
                size: '10000人以上',
                recommend: 88,
                hot: 85,
                latest: 83,
                bgColor: '#E3F2FD'
            },
            {
                id: 16,
                name: '招商银行',
                logo: 'https://source.unsplash.com/featured/400x300/?commerce,bank/16',
                region: 'south',
                type: 'finance',
                features: ['金融', '银行', '理财'],
                size: '5000-10000人',
                recommend: 94,
                hot: 91,
                latest: 87,
                bgColor: '#F3E5F5'
            },
            {
                id: 17,
                name: '联想集团',
                logo: 'https://source.unsplash.com/featured/400x300/?computer,tech/17',
                region: 'north',
                type: 'hardware',
                features: ['电子', '计算机', '国际化'],
                size: '5000-10000人',
                recommend: 87,
                hot: 84,
                latest: 82,
                bgColor: '#E1F5FE'
            },
            {
                id: 18,
                name: '海尔集团',
                logo: 'https://source.unsplash.com/featured/400x300/?appliance,home/18',
                region: 'east',
                type: 'manufacturing',
                features: ['电器', '家居', '制造'],
                size: '10000人以上',
                recommend: 86,
                hot: 83,
                latest: 81,
                bgColor: '#F1F8E9'
            },
            {
                id: 19,
                name: '格力电器',
                logo: 'https://source.unsplash.com/featured/400x300/?airconditioner,appliance/19',
                region: 'south',
                type: 'manufacturing',
                features: ['电器', '空调', '制造'],
                size: '5000-10000人',
                recommend: 85,
                hot: 82,
                latest: 80,
                bgColor: '#E0F7FA'
            },
            {
                id: 20,
                name: '顺丰速运',
                logo: 'https://source.unsplash.com/featured/400x300/?delivery,logistics/20',
                region: 'south',
                type: 'service',
                features: ['物流', '快递', '服务'],
                size: '10000人以上',
                recommend: 90,
                hot: 89,
                latest: 88,
                bgColor: '#FFFDE7'
            },
            {
                id: 21,
                name: '中兴通讯',
                logo: 'https://source.unsplash.com/featured/400x300/?telecom,communication/21',
                region: 'south',
                type: 'hardware',
                features: ['通信', '设备', '研发'],
                size: '5000-10000人',
                recommend: 84,
                hot: 80,
                latest: 78,
                bgColor: '#F9FBE7'
            },
            {
                id: 22,
                name: '京东方',
                logo: 'https://source.unsplash.com/featured/400x300/?display,screen/22',
                region: 'north',
                type: 'hardware',
                features: ['显示', '面板', '制造'],
                size: '10000人以上',
                recommend: 83,
                hot: 78,
                latest: 77,
                bgColor: '#FBE9E7'
            },
            {
                id: 23,
                name: '比亚迪',
                logo: 'https://source.unsplash.com/featured/400x300/?car,electric/23',
                region: 'south',
                type: 'manufacturing',
                features: ['汽车', '新能源', '电池'],
                size: '10000人以上',
                recommend: 89,
                hot: 87,
                latest: 85,
                bgColor: '#E8EAF6'
            },
            {
                id: 24,
                name: '宁德时代',
                logo: 'https://source.unsplash.com/featured/400x300/?battery,energy/24',
                region: 'east',
                type: 'manufacturing',
                features: ['电池', '新能源', '制造'],
                size: '5000-10000人',
                recommend: 92,
                hot: 90,
                latest: 89,
                bgColor: '#E3F2FD'
            }
        ];
        
        const companyList = document.querySelector('#company-list');
        if (!companyList) {
            throw new Error('找不到企业列表容器');
        }
        
        // 清空现有内容
        companyList.innerHTML = '';
        
        // 添加公司卡片
        companies.forEach(company => {
            const card = createCompanyCard(company);
            companyList.appendChild(card);
        });
        
        // 隐藏加载动画
        setTimeout(() => {
            showLoading(false);
        }, 800);
        
        // 添加卡片出现动画
        animateCards(companyList);
        
        // 确保所有图片正确加载
        setTimeout(() => {
            handleImageErrors();
        }, 1000);
        
    } catch (error) {
        console.error('加载企业数据失败:', error);
        showLoading(false);
        showNoResults();
    }
}

/**
 * 创建企业卡片
 */
function createCompanyCard(company) {
    const card = document.createElement('div');
    card.className = 'institution-card company-card fade-in';
    card.setAttribute('data-region', company.region);
    card.setAttribute('data-type', company.type);
    card.setAttribute('data-features', company.features ? company.features.join(',') : '');
    card.setAttribute('data-recommend', company.recommend);
    card.setAttribute('data-hot', company.hot);
    card.setAttribute('data-latest', company.latest);
    
    // 添加背景渐变
    card.style.background = `linear-gradient(135deg, ${company.bgColor || '#ffffff'} 0%, #ffffff 100%)`;
    
    // 随机决定是否显示徽章（约30%的卡片会显示）
    const showBadge = Math.random() > 0.7;
    const badgeText = showBadge ? (company.hot > 95 ? '热门企业' : '知名企业') : '';
    
    // 确保有有效的图片URL
    const companyId = company.id || Math.floor(Math.random() * 1000);
    const logoUrl = `https://source.unsplash.com/featured/400x300/?company,office/${companyId}`;
    
    card.innerHTML = `
        <div class="institution-logo-container">
            <img src="${logoUrl}" alt="${company.name}" class="institution-logo" loading="lazy">
            ${showBadge ? `<div class="institution-badge">${badgeText}</div>` : ''}
            <div class="institution-overlay"></div>
        </div>
        <div class="institution-info">
            <h3 class="institution-name">${company.name}</h3>
            <div class="institution-type">${getCompanyTypeName(company.type)} · ${getRegionName(company.region)}</div>
            <div class="institution-features">
                ${company.features ? company.features.map(feature => `<span class="feature-tag"><i class="iconfont icon-business"></i>${feature}</span>`).join('') : ''}
                ${company.size ? `<span class="feature-tag"><i class="iconfont icon-team"></i>${company.size}</span>` : ''}
            </div>
            <div class="institution-stats">
                <div class="stats-item"><i class="iconfont icon-star"></i> ${company.recommend}分</div>
                <div class="stats-item"><i class="iconfont icon-fire"></i> ${company.hot * 10}热度</div>
            </div>
        </div>
    `;
    
    // 添加点击事件
    card.addEventListener('click', function(event) {
        // 添加点击涟漪效果
        createRippleEffect(this, event);
        // 延迟跳转，以便显示动画
        setTimeout(() => {
            // 跳转到企业详情页
            window.location.href = `company-detail.html?id=${company.id}`;
        }, 300);
    });
    
    return card;
}

/**
 * 获取地区名称
 */
function getRegionName(regionCode) {
    const regions = {
        'north': '华北',
        'east': '华东',
        'south': '华南',
        'central': '华中',
        'southwest': '西南',
        'northwest': '西北',
        'northeast': '东北'
    };
    
    return regions[regionCode] || regionCode;
}

/**
 * 获取院校类型名称
 */
function getTypeName(typeCode) {
    const types = {
        'comprehensive': '综合类',
        'engineering': '理工类',
        'agriculture': '农林类',
        'medicine': '医药类',
        'normal': '师范类',
        'finance': '财经类',
        'art': '艺术类',
        'language': '语言类',
        'politics': '政法类'
    };
    
    return types[typeCode] || typeCode;
}

/**
 * 获取企业类型名称
 */
function getCompanyTypeName(typeCode) {
    const types = {
        'internet': '互联网',
        'finance': '金融',
        'hardware': '硬件制造',
        'software': '软件开发',
        'service': '服务业',
        'consulting': '咨询',
        'education': '教育',
        'manufacturing': '制造业',
        'medical': '医疗健康'
    };
    
    return types[typeCode] || typeCode;
}

/**
 * 处理图片加载错误
 */
function handleImageErrors() {
    // 生成随机ID函数
    function generateRandomId() {
        return Math.floor(Math.random() * 1000);
    }
    
    // 预处理所有图片
    const images = document.querySelectorAll('img');
    
    images.forEach(img => {
        // 立即处理已经损坏的图片
        if (img.complete && (img.naturalWidth === 0 || img.naturalHeight === 0)) {
            replaceWithAlternativeImage(img);
        }
        
        // 为未来可能的错误添加事件监听器
        img.onerror = function() {
            replaceWithAlternativeImage(this);
        };
        
        // 添加加载完成后的处理
        img.onload = function() {
            this.classList.add('image-loaded');
            const container = this.closest('.institution-logo-container');
            if (container) {
                container.classList.add('image-loaded');
            }
        };
    });
    
    // 替换图片的函数
    function replaceWithAlternativeImage(imgElement) {
        // 确定图片类型和相应的替代图片
        const cardElement = imgElement.closest('.institution-card');
        const randomId = generateRandomId();
        let category = 'campus';
        
        // 根据卡片类型确定适当的图片类别
        if (cardElement) {
            if (cardElement.classList.contains('school-card')) {
                category = 'university/campus';
            } else if (cardElement.classList.contains('company-card')) {
                // 根据企业类型决定不同的图片类别
                const companyType = cardElement.getAttribute('data-type');
                switch(companyType) {
                    case 'tech':
                        category = 'technology/office';
                        break;
                    case 'finance':
                        category = 'finance/business';
                        break;
                    case 'consulting':
                        category = 'consulting/professional';
                        break;
                    case 'manufacturing':
                        category = 'manufacturing/industry';
                        break;
                    default:
                        category = 'company/corporate';
                }
            }
        }
        
        // 检查元素是否是机构标志
        if (imgElement.classList.contains('institution-logo')) {
            // 使用高质量的标志图像
            imgElement.src = `https://source.unsplash.com/featured/400x300/?${category}/${randomId}`;
        } else if (imgElement.classList.contains('avatar') || imgElement.parentElement?.classList.contains('avatar-container')) {
            // 头像图片使用专业的头像服务
            imgElement.src = `https://i.pravatar.cc/150?img=${randomId % 70}`;
            imgElement.style.objectFit = 'cover';
            imgElement.style.borderRadius = '50%';
        } else {
            // 其他类型的图片
            imgElement.src = `https://source.unsplash.com/random/800x600/?${category}/${randomId}`;
        }
        
        // 设置为急切加载以提高优先级
        imgElement.loading = 'eager';
        
        // 添加动画效果
        imgElement.classList.add('image-loading');
        setTimeout(() => {
            imgElement.classList.remove('image-loading');
            imgElement.classList.add('image-loaded');
        }, 500);
    }
    
    // 主动检查当前页面中的所有实例图片是否已加载
    setTimeout(() => {
        document.querySelectorAll('.institution-logo').forEach(img => {
            if (img.complete && img.naturalHeight === 0) {
                replaceWithAlternativeImage(img);
            }
        });
    }, 100);
}

// 添加显示无结果状态的函数
function showNoResults() {
    const noResults = document.querySelector('.no-results');
    if (noResults) {
        noResults.style.display = 'block';
    }
}

// 添加显示/隐藏加载动画的函数
function showLoading(show) {
    const loadingSpinner = document.querySelector('.loading-spinner');
    if (loadingSpinner) {
        loadingSpinner.style.display = show ? 'block' : 'none';
    }
}

// 添加卡片动画函数
function animateCards(container) {
    const cards = container.querySelectorAll('.institution-card');
    
    // 检查是否有IntersectionObserver支持
    if ('IntersectionObserver' in window) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                // 当卡片进入视口时添加可见类
                if (entry.isIntersecting) {
                    setTimeout(() => {
                        entry.target.classList.add('card-visible');
                    }, 100); // 添加小延迟使动画更平滑
                    observer.unobserve(entry.target); // 只触发一次
                }
            });
        }, { threshold: 0.1 }); // 当10%的卡片进入视口时触发
        
        cards.forEach(card => {
            observer.observe(card);
        });
    } else {
        // 回退方案：简单的延迟显示
        cards.forEach((card, index) => {
            setTimeout(() => {
                card.classList.add('card-visible');
            }, index * 100);
        });
    }
    
    // 主动触发一次遍历，确保已在视口中的卡片立即显示
    setTimeout(() => {
        cards.forEach((card, index) => {
            // 检查卡片是否在视口中
            const rect = card.getBoundingClientRect();
            const isInViewport = (
                rect.top >= 0 &&
                rect.left >= 0 &&
                rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
                rect.right <= (window.innerWidth || document.documentElement.clientWidth)
            );
            
            if (isInViewport && !card.classList.contains('card-visible')) {
                setTimeout(() => {
                    card.classList.add('card-visible');
                }, index * 50); // 更短的延迟
            }
        });
    }, 200);
} 